#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : wupeiqi_async
@File : ai_optimization.py
@Author : Royce
@Time : 2025/7/13 15:28  
@脚本说明 : 
"""
import asyncio
import aioredis
from aioredis import RedisError


async def execute(address, password):
    print(f"开始连接Redis服务器: {address}")

    try:
        # 使用连接池管理连接（提高性能）[4,7](@ref)
        redis = await aioredis.from_url(
            address,
            password=password,
            db=0,
            decode_responses=True,  # 自动转字符串
            max_connections=10  # 连接池大小
        )
        print("✓ Redis连接成功")

        # 设置哈希值（使用hset替代hmset）[1,7](@ref)
        await redis.hset('car', mapping={'key1': 1, 'key2': 2, 'key3': 3})
        print("✓ 哈希值设置成功")

        # 获取全部哈希值（添加类型注解）[6,8](@ref)
        result: dict = await redis.hgetall('car')
        print(f'取出car数据: {result}')  # 直接输出字典

    except RedisError as e:
        print(f"! Redis操作失败: {e}")
    finally:
        # 确保连接关闭（使用wait_closed）[4,5](@ref)
        if 'redis' in locals():
            await redis.close()
            await redis.wait_closed()
            print("✓ Redis连接已释放")

    print(f"操作完成: {address}")


if __name__ == '__main__':
    # 添加全局异常处理[5](@ref)
    try:
        asyncio.run(execute('redis://192.168.88.66:6379', "666888"))
    except Exception as e:
        print(f"! 程序异常: {e}")
